package com.app.lxx.pregnancyberth.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.lxx.pregnancyberth.Mvp.Presenter.CurrencyPresenter;
import com.app.lxx.pregnancyberth.Mvp.View.CurrencyView;
import com.app.lxx.pregnancyberth.R;
import com.app.lxx.pregnancyberth.base.BaseActivity;
import com.app.lxx.pregnancyberth.base.UrlManage;
import com.app.lxx.pregnancyberth.easyphone.EasyLinphone;
import com.app.lxx.pregnancyberth.easyphone.callback.PhoneCallback;
import com.app.lxx.pregnancyberth.easyphone.callback.RegistrationCallback;
import com.app.lxx.pregnancyberth.easyphone.service.LinphoneService;
import com.app.lxx.pregnancyberth.ui.entity.AddDeviceEntity;
import com.app.lxx.pregnancyberth.utils.NetUtils;
import com.app.lxx.pregnancyberth.utils.PermissionManager;
import com.app.lxx.pregnancyberth.widge.LoadDailog.LoadDialog;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.yanzhenjie.permission.Permission;

import java.util.HashMap;

/**
 * Created by Lxx on PregnancyBerth
 * 2019/8/26 11:25 星期三
 * Details：管理员界面
 */
public class ControllerActivity extends BaseActivity<CurrencyPresenter> implements CurrencyView {

    private LinearLayout loginly;
    private EditText messageEdtv;
    private Button messageLogin;
    private Button messageOut;
    private LinearLayout infoly;
    private TextView infoXtgl;
    private TextView infoSbxx;
    private LinearLayout xtglLy;
    private TextView xtglFwqip;
    private EditText sipDuankou;
    private EditText xtglXgmm;
    private Button btnSubmitXtgl;
    private Button btnCloseXtgl;
    private LinearLayout sbxxLy;
    private TextView sbxxTv;
    private EditText sbxxFjh;
    private EditText sbxxCwh;
    private Button btnSubmitSbxx;
    private Button btnCloseSbxx;
    private EditText sipServer;
    private EditText sipAccount;
    private EditText sipPassword;
    private EditText sipServersjk;
    private TextView bindNursenumber;
    private boolean manageMode = false;


    @Override
    protected CurrencyPresenter createP() {
        return new CurrencyPresenter();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        manageMode = getIntent().getBooleanExtra("manageMode", false);
    }

    @Override
    protected void initBindViewId() {
        try {
            initView();
            xtglFwqip.setText(NetUtils.getIPAddress(this));
            if (!TextUtils.isEmpty(shareference.getHouseName())) {
                sbxxFjh.setText(shareference.getHouseName());
            }
            if (!TextUtils.isEmpty(shareference.getBedName())) {
                sbxxCwh.setText(shareference.getBedName());
            }

            String linPhonDataIp = shareference.getLinPhonDataIp();

            if (!TextUtils.isEmpty(linPhonDataIp)) {
                sipAccount.setText(shareference.getLinPhonDataZh());
                sipPassword.setText(shareference.getLinPhonDataMm());
                sipServer.setText(linPhonDataIp);
                sipDuankou.setText(shareference.getLinPhonDataDq());
            }

            initPermission();
            initLinPhone();
            onClickList();
            if (!manageMode) {
                autoLogin();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void autoLogin() {
        String account = sipAccount.getText().toString();
        String password = sipPassword.getText().toString();
        String serverIP = sipServer.getText().toString();
        String sipDk = sipDuankou.getText().toString();
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(serverIP) && !TextUtils.isEmpty(sipDk)) {
            EasyLinphone.setAccount(account, password, serverIP + ":" + "5060");
            EasyLinphone.login();
        }
    }

    long last = 0;

    private void initLinPhone() {
        /**
         * 系统信息
         */
        EasyLinphone.addCallback(new RegistrationCallback() {
            @Override
            public void registrationOk() {
                super.registrationOk();
                showToast("登录成功！");


                if (sbxxLy.getVisibility() != View.VISIBLE) {
                    sbxxLy.setVisibility(View.VISIBLE);
                }
                if (xtglLy.getVisibility() != View.GONE) {
                    xtglLy.setVisibility(View.GONE);
                }

                infoSbxx.setBackgroundColor(getResources().getColor(R.color.botton_DBD8D8));
                infoXtgl.setBackgroundColor(getResources().getColor(R.color.botton_999797));
                String house_num = sbxxFjh.getText().toString(); //	房间号
                String bed_num = sbxxCwh.getText().toString();    //床位号
                String device_id = shareference.getLinPhonDataZh();//   	设备ID
                if (!TextUtils.isEmpty(house_num) && !TextUtils.isEmpty(bed_num) && !TextUtils.isEmpty(device_id)) {
                    if (!manageMode) {
                        requestSubmitData();
                    }
                }
            }

            @Override
            public void registrationFailed() {
                LoadDialog.dismiss(context);
                super.registrationFailed();
                showToast("登录失败！");
            }

            @Override
            public void registrationProgress() {
                super.registrationProgress();
                LoadDialog.show(context, "登录中");
            }

            @Override
            public void registrationNone() {
                super.registrationNone();
            }

            @Override
            public void registrationCleared() {
                super.registrationCleared();
            }
        }, new PhoneCallback() {
        });
    }

    private void onClickList() {
        messageLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (messageEdtv.getText().toString().equals("123456")) {
                    loginly.setVisibility(View.GONE);
                    infoly.setVisibility(View.VISIBLE);
                } else {
                    showToast("密码错误");
                }
            }
        });

        messageOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        infoXtgl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (xtglLy.getVisibility() != View.VISIBLE) {
                    xtglLy.setVisibility(View.VISIBLE);
                }
                if (sbxxLy.getVisibility() != View.GONE) {
                    sbxxLy.setVisibility(View.GONE);
                }

                infoXtgl.setBackgroundColor(getResources().getColor(R.color.botton_DBD8D8));
                infoSbxx.setBackgroundColor(getResources().getColor(R.color.botton_999797));
            }
        });
        infoSbxx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sbxxLy.getVisibility() != View.VISIBLE) {
                    sbxxLy.setVisibility(View.VISIBLE);
                }
                if (xtglLy.getVisibility() != View.GONE) {
                    xtglLy.setVisibility(View.GONE);
                }

                infoSbxx.setBackgroundColor(getResources().getColor(R.color.botton_DBD8D8));
                infoXtgl.setBackgroundColor(getResources().getColor(R.color.botton_999797));
            }
        });
        btnSubmitXtgl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String bindNurseAccount = shareference.getBindNurseUser();
                if (TextUtils.isEmpty(bindNurseAccount)) {
                    showToast("未绑定护士账号");
                    return;
                }

                AlertDialog alertDialog = new AlertDialog.Builder(ControllerActivity.this).create();
                alertDialog.setTitle("温馨提示");
                alertDialog.setMessage("请确认信息是否正确");
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String account = sipAccount.getText().toString();
                        String password = sipPassword.getText().toString();
                        String serverIP = sipServer.getText().toString();
                        String sipDk = sipDuankou.getText().toString();
                        Bundle bundle = new Bundle();
                        bundle.putString("serviceIp", serverIP);//ip
                        bundle.putString("serviceDq", sipDk);//端口
                        bundle.putString("serviceZh", account);//账号
                        bundle.putString("serviceMm", password);//密码
                        shareference.saveLinPhonData(bundle);
                        EasyLinphone.setAccount(account, password, serverIP + ":" + "5060");
                        EasyLinphone.login();
                    }
                });
                alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                alertDialog.setCancelable(false);
                alertDialog.show();
            }
        });
        btnCloseXtgl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VoipP2PActivity.newInstance(context);
            }
        });

        /**
         * 设备信息
         */
        btnSubmitSbxx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestSubmitData();
            }
        });
        btnCloseSbxx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VoipP2PActivity.newInstance(context);
            }
        });
    }

    @Override
    protected boolean hidetitle() {
        return true;
    }

    @Override
    protected String settitle() {
        return "管理员界面";
    }

    @NonNull
    @Override
    public int setxmlview() {
        return R.layout.activity_register;
    }

    /**
     * 初始化权限事件
     */
    private void initPermission() {
        //检查权限
        PermissionManager.requestPermission(ControllerActivity.this, new PermissionManager.Callback() {
            @Override
            public void permissionSuccess() {
                PermissionManager.requestPermission(ControllerActivity.this, new PermissionManager.Callback() {
                    @Override
                    public void permissionSuccess() {
                        PermissionManager.requestPermission(ControllerActivity.this, new PermissionManager.Callback() {
                            @Override
                            public void permissionSuccess() {

                            }

                            @Override
                            public void permissionFailed() {
                            }
                        }, Permission.Group.STORAGE);
                    }

                    @Override
                    public void permissionFailed() {

                    }
                }, Permission.Group.MICROPHONE);
            }

            @Override
            public void permissionFailed() {

            }
        }, Permission.Group.CAMERA);
    }

    /**
     * 提交设备信息 /api/common/add_device
     */
    private final int add_device = 1;

    private void requestSubmitData() {
        if (System.currentTimeMillis() - last > 1000) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("house_num", sbxxFjh.getText().toString()); //	房间号
            hashMap.put("bed_num", sbxxCwh.getText().toString());//   	床位号
            hashMap.put("device_id", shareference.getLinPhonDataZh());//   	设备ID
            hashMap.put("nurse", shareference.getBindNurseUser());//   	护士账号
            if (utilsManage.isNull(hashMap)) {
                showToast("信息未填写完整");
            } else {
                shareference.saveUserNameInfo(sbxxFjh.getText().toString(), sbxxCwh.getText().toString());
                getP().requestGet(add_device, UrlManage.APP_URL + "common/add_device", hashMap);
            }
        }
        last = System.currentTimeMillis();
    }

    /**
     * 查看设备是否绑定床位 /api/index/deviceinfo
     */
    private final int index_deviceinfo = 2;

    private void requestIndexData(String bed_id) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("bed_id", bed_id);//   	床位id
        if (utilsManage.isNull(hashMap)) {

        } else {
            getP().requestGet(index_deviceinfo, UrlManage.APP_URL + "index/deviceinfo", hashMap);
        }
    }


    @Override
    public void requestCurrencyView(int type, String body) {
        Log.e("sss", "type:" + type + "\nbody:" + body);
        switch (type) {
            case add_device:
                AddDeviceEntity addDeviceEntity = new Gson().fromJson(body, AddDeviceEntity.class);
                int code = addDeviceEntity.getCode();
                if (code == 1 || code == 3) {
                    shareference.saveUserLoginInfo(addDeviceEntity.getData());
                    VoipP2PActivity.newInstance(this);
                } else {
                    showToast("床位已绑定");
                    requestIndexData(addDeviceEntity.getData().getBed_id() + "");
                }

                break;
            case index_deviceinfo:
                ToastUtils.showShort(body);
                break;
        }
    }

    @Override
    public void requestCurrencyViewFailed(int type, int code) {

    }

    private void initView() {
        loginly = findViewById(R.id.loginly);
        View tv_exitApp = findViewById(R.id.tv_exitApp);
        tv_exitApp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast("系统设置");
                startActivity(new Intent(Settings.ACTION_SETTINGS));
            }
        });
        messageEdtv = findViewById(R.id.message_edtv);
        messageLogin = findViewById(R.id.message_login);
        messageOut = findViewById(R.id.message_out);

        infoly = findViewById(R.id.infoly);
        infoXtgl = findViewById(R.id.info_xtgl);
        infoSbxx = findViewById(R.id.info_sbxx);
        xtglLy = findViewById(R.id.xtgl_ly);
        xtglFwqip = findViewById(R.id.xtgl_fwqip);
        sipDuankou = findViewById(R.id.sip_duankou);
        xtglXgmm = findViewById(R.id.xtgl_xgmm);
        btnSubmitXtgl = findViewById(R.id.btn_submit_xtgl);
        btnCloseXtgl = findViewById(R.id.btn_close_xtgl);

        sbxxLy = findViewById(R.id.sbxx_ly);
        sbxxTv = findViewById(R.id.sbxx_tv);
        sbxxFjh = findViewById(R.id.sbxx_fjh);
        sbxxCwh = findViewById(R.id.sbxx_cwh);
        btnSubmitSbxx = findViewById(R.id.btn_submit_sbxx);
        btnCloseSbxx = findViewById(R.id.btn_close_sbxx);

        sipServer = findViewById(R.id.sip_server);
        sipAccount = findViewById(R.id.sip_account);
        sipPassword = findViewById(R.id.sip_password);

        sipServersjk = findViewById(R.id.sip_serversjk);
        bindNursenumber = findViewById(R.id.bind_nursenumber);
        TextView bind_nursesubmit = findViewById(R.id.bind_nursesubmit);

        String serviceIp = shareference.getServiceIp();
        if (!TextUtils.isEmpty(serviceIp)) {
            sipServersjk.setText(serviceIp);
        }
        String bindNurseAccount = shareference.getBindNurseUser();
        if (!TextUtils.isEmpty(bindNurseAccount)) {
            bindNursenumber.setText(bindNurseAccount);
        }

        bind_nursesubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareference.saveBindNurseUser(bindNursenumber.getText().toString());
                showToast("已绑定护士端");
            }
        });

        findViewById(R.id.fuqbaocun).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = sipServersjk.getText().toString();
                shareference.saveServiceIp(s);
                UrlManage.imageUrl = "http://" + s;
                UrlManage.APP_URL = "http://" + s + "/api/";
                showToast("服务器IP=>" + UrlManage.APP_URL);

            }
        });

//        infoly.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (System.currentTimeMillis() - firstPressedTime < 1500) {
//                    clickNum++;
//                    if (clickNum == 3) {
//                        final EditText inputServer = new EditText(context);
//
//                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
//                        builder.setTitle("Server")
//                                .setIcon(android.R.drawable.ic_dialog_info)
//                                .setView(inputServer)
//                                .setCancelable(false)
//                                .setNegativeButton("Cancel", null);
//                        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                        }
//                        });
//                        builder.show();
//                    }
//                } else {
//                    clickNum = 0;
//                    firstPressedTime = System.currentTimeMillis();
//                }
//            }
//        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EasyLinphone.onDestroy();
    }
}
